<template>
    <pageTabelLayout>
        <template #pageHeader>
            <div class="search-form divClass" v-if="headerShow">
                <div>
                <a-form size="small" :model="pageData" layout="inline">
                    <a-form-item label="设备编号">
                        <!-- <a-select popup-container="html"  class="bacClass" :style="{ width: '200px' }" :loading="loading" @search="handleSearch"
                            v-model="pageData.dropDownData" :filter-option="false" allow-search allow-clear
                            @focus="focusSel">
                            <a-option v-for="item in pageData.nameList" :value="item">{{ item }}</a-option>
                        </a-select> -->
                        <a-input allow-clear :style="{ width: '200px' }" class="bacClass" placeholder=""
                            v-model="pageData.dropDownData" @press-enter="huiche" />
                    </a-form-item>
                </a-form>
            </div>
            <div class="my-tool-bar">
                <Toolbar style="float:right" :items="['查询', '新增', '删除']" @add="addHandler" @del="deleteHandler" @select="selectHandler"
                    @export="exports" @import="importHandler" @excel="downloadHandler">
                </Toolbar>
            </div>
        </div>
            <div class="my-divisders">
                <a-divider orientation="center">
                    <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18" />
                    <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18" />
                </a-divider>
            </div>
        </template>
        <template #pageTabel>
            <!-- <a-tabs   :justify="true">
                <a-tab-pane> -->
                      <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true" rowSelection="multiple" @grid-ready="gridReady" style="height:100%"
                        :defaultColDef="defaultColDef" class='ag-theme-alpine' :rowData="table.dataList"
                        :columnDefs="tc" :localeText="localeText1"></AgGridVuesCopys>
                <!-- </a-tab-pane>
            </a-tabs> -->
        </template>
        <paginationCopys :page-size="pagination.pageSize" :current="pagination.page" :total="total" show-total show-jumper show-page-size @change="PageSize"
            @page-size-change="change1" style="justify-content: center" />

        <a-drawer ok-text='保存' cancel-text='关闭' :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" :width="400"
            :ok-loading="pageData.pageLoading" :visible="pageData.showAdd" unmountOnClose @ok="sideOk"
            @cancel="pageData.showAdd = false">
            <template #title>
                {{ pageData.sideTitle }}
            </template>
            <div>
                <a-form ref="formRef" layout="horizontal" :model="dataForm">
                    <a-form-item label-col-flex="100px" label="设备编号" field="controlMachineCode"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '设备编号必填' }]">
                        <a-select popup-container="html"  class="bacClass" placeholder=" " v-model="dataForm.controlMachineCode"
                            @focus="focusSel1" @search="handleSearch1" @change="sbChange"
                            :loading1="loading1" allow-clear>
                            <a-option v-for="item in pageData.CodeList" :value="item.id">
                                {{ item.controlMachineCode }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="100px" label="设备名称" field="controlMachineName"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '设备名称必填' }]">
                        <a-select popup-container="html"  class="bacClass" placeholder=" " v-model="dataForm.controlMachineName"
                            @search="handleSearch1" @focus="NameFocus" @click="NameClick" :loading1="loading1" allow-clear>
                            <a-option v-for="item in pageData.NameList" :value="item.controlMachineName">
                                {{ item.controlMachineName }}
                            </a-option>
                        </a-select>
                    </a-form-item>
                    <a-form-item label-col-flex="100px" label="二维码内容" field="qrCode"
                        :validate-trigger="['change', 'blur']" :rules="[{ required: true, message: '二维码内容必填' }]">
                        <a-input class="bacClass" placeholder=" " v-model="dataForm.qrCode" />
                    </a-form-item>
                    <a-form-item label-col-flex="100px" label="备注">
                        <a-textarea class="bacClass" v-model="dataForm.remark" :max-length="400" allow-clear show-word-limit/>
                    </a-form-item>
                </a-form>
            </div>
        </a-drawer>
        <a-modal :visible="visible" @ok="handleOk" @cancel="handleCancel" okText="打印" cancelText="关闭" unmountOnClose>
            <template #title>
                生成标签
            </template>
            <div id="genera" >
                <QrcodeVue :value="qrData.code"></QrcodeVue>
                <div style="display:inline-block;vertical-align:top;width:300px;margin-left:15px;line-height:2.5em;">
                    <span>设备编号: {{ decodeURI(qrData.controlMachineCode)  }}</span>
                    <br />
                    <span>设备名称: {{ decodeURI(qrData.controlMachineName) }}</span>
                    <br />
                    <span>二维码内容: {{ decodeURI(qrData.qrCode) }}</span>
                    <br />
                </div>      
            </div>
        </a-modal>
    </pageTabelLayout>
</template>

<script lang="ts">
import { post } from '@/api/http'
import { useTable, useRowKey, useTableColumn, usePagination, useRowSelection } from '@/hooks/table';
import emitter from "@/hooks/useEventBus";
import { ref, reactive, onMounted, toRefs } from 'vue'
import Toolbar from '@/components/Toolbar.vue';
import { Form, Message, Modal } from '@arco-design/web-vue';
import { FormInstance } from '@arco-design/web-vue/es/form';
import { baseURL } from '../../../../api/axios.config'
import axios from "axios";
import filedownload from 'js-file-download'
import usePermission from '@/store/modules/permission'
import PageTabelLayout from '@/components/pageTabelLayout.vue';
import { AnyARecord } from 'dns';

import printJS from 'print-js'
import QrcodeVue from 'qrcode.vue'
import {localeText} from '@/api/aggridZw'
interface BrandInfo {
    "id": any,
    "remark": any,
    "createName": string | undefined,
    "createTime": string | undefined,
    "updateName": string | undefined,
    "updateTime": string | undefined,
    "deleteState": any,
    "obsoleteState": any,
    "serial": any,
    "controlMachineCode": any,
    "controlMachineName": any,
    "qrCode":any,
}

export default {
    name: "GenerationQRcode",
    setup() {
        const total = ref(10);
        const page = ref(1);
        const size = ref(10);
        function PageSize(val: any) {
            pagination.page = val
            doRefresh();
        }

        function change1(val: any) {
            pagination.pageSize = val
            doRefresh();
        }
        const headerShow = ref<boolean>(true)
        //查询方法
        function doRefresh() {

            pageData.pageLoading = true
            post({
                url: "/pdm/CreateQrcode/getPage",
                data: {
                    page: pagination.page,
                    size: pagination.pageSize,
                    deleteState: "0",
                    controlMachineCode: pageData.dropDownData
                },
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        table.handleSuccess(data.list);
                        // pagination.setTotalSize(data.total);
                        gridOption.value.setRowData(data.list);
                        total.value = data.total;
                    }
                })
                .catch(console.log).finally(() => {
                    pageData.pageLoading = false
                })
        }

        const { selectedRowKeys, onSelectionChange } = useRowSelection();
        const pagination = usePagination(doRefresh);
        const table = useTable();
        const rowKey = useRowKey("id");
        const tableColumns = useTableColumn([
            {
                title: "序号",
                key: "id",
                dataIndex: "id",
                width: 150,
            },
            {
                title: "设备编号",
                key: "controlMachineCode",
                dataIndex: "controlMachineCode",
                width: 150
            },
            {
                title: "设备名称",
                key: "controlMachineName",
                dataIndex: "controlMachineName",
                width: 150
            },
            {
                title: "二维码内容",
                key: "qrCode",
                dataIndex: "qrCode",
                width: 150
            },
            {
                title: "备注",
                key: "remark",
                dataIndex: "remark",
                width: 150
            },
            {
                title: "创建人",
                key: "createName",
                dataIndex: "createName",
                width: 150
            },
            {
                title: "创建时间",
                key: "createTime",
                dataIndex: "createTime",
                width: 200
            },
            {
                title: "最后修改人",
                key: "updateName",
                dataIndex: "updateName",
                width: 150
            },
            {
                title: "最后修改时间",
                key: "updateTime",
                dataIndex: "updateTime",
                width: 200
            },
            {
                title: '操作',
                key: "id",
                slotName: 'act',
                width: 150, fixed: 'right'
            }
        ]);
        let tc: any[] = tableColumns.map((o) => {

            let obj = {
                headerName: o.title,
                field: o.key,
                pinned: o['fixed']
            }
            if (o.slotName === 'act') {
                obj['resizable'] = false
                obj['filter'] = false
                obj['sortable'] = false
                obj["lockPosition"] = "right"
                obj["width"] = 140
                obj['cellRenderer'] = {
                    template: `<a-space>
                                   <a-tag color="#ff7d00" @click="a1" class="gesture">修改</a-tag>
                                   <a-tag color="#2961dc" @click="a2" class="gesture">生成标签</a-tag>
                               </a-space>`,
                    setup(props: any) {
                        const a1 = () => {
                            editHandler(props.params.data)
                        }
                        const a2 = () => {
                            GenerateBtn(props.params.data)
                        }
                        return {
                            a1,
                            a2
                        }
                    }

                }
            }

            return obj
        })



        let a = [{
            showRowGroup: 'hide_def',
            "headerName": "",
            "checkboxSelection": true,
            "headerCheckboxSelection": true,
            "pinned": "left",
            "width": 50,
            resizable: false,
            filter: false,
            sortable: false,
            minWidth: 50,
            maxWidth: 50,
            lockPosition: "left",
        }]
        tc = a.concat(tc)

        const pageData = reactive<{
            showAdd: boolean,
            sideTitle: string,
            dropDownData: any,
            nameList: [],
            pageLoading: boolean,
            typeList: [],
            dropDownData1: any,
            rHeight: any,
            btnList: any[],
            isEdit: boolean,
            CodeList: any[],
            NameList: any[],
        }>({
            nameList: [],
            showAdd: false,
            sideTitle: '新增二维码',
            dropDownData: "",
            pageLoading: false,
            typeList: [],
            dropDownData1: "",
            rHeight: 0,
            btnList: [],
            isEdit: false,
            CodeList: [],
            NameList: [],
        });

        interface gcType {
            id: any,
            company: any,
        }
        //下拉框得到焦点
        const focusSel = () => {
            selCxAll({ "controlMachineCode": "", deleteState: 0 });
        }

        //下拉数据
        const options = ref<any>(pageData.nameList);
        const loading = ref(false);
        const handleSearch = (value: any) => {
            if (value) {
                const ob = { controlMachineCode: value, deleteState: 0 }
                loading.value = true;
                selCxAll(ob);
                options.value = pageData.nameList;
                loading.value = false;
            } else {
                options.value = []
            }
        };
        //下拉框查询
        function selCxAll(val: any) {
            post({
                url: "/pdm/CreateQrcode/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    console.log(data);
                    let dataList: any = [];
                    data.forEach(function (o: any) {
                        dataList.push(o["controlMachineCode"])
                    });
                    pageData.nameList = dataList;
                } else {
                    Message.error({
                        content: "查询失败！",
                        duration: 5000,
                    });
                }
            });
        }

        onMounted(() => {
            // 切换tap到本页面执行的方法
            emitter.on("GenerationQRcode", () => {
                // selCxAll({});
                doRefresh();
            });
        });

        let cxbl = {}
        //查询
        const selectHandler = () => {
            pagination.page = 1
            cxbl = pageData.dropDownData
            doRefresh();
        }
        const queryData = reactive({
            controlMachineCode: ""
        });
        const addHandler = () => {
            selCxAll1({ controlMachineCode: "" })
            for (var key in dataForm) {
                if (key === "id") {
                    dataForm[key] = null;
                } else {
                    dataForm[key] = "";
                }
            }
            pageData.showAdd = true
            pageData.sideTitle = '新增二维码'
        }
        const dataForm = reactive<BrandInfo>({
            "id": null,
            "remark": "",
            "createName": "",
            "createTime": "",
            "updateName": "",
            "updateTime": "",
            "deleteState": 0,
            "obsoleteState": "",
            "serial": 0,
            "controlMachineCode": null,
            "controlMachineName": "",
            "qrCode":""
        })

        // 表格准备事件
        const gridOption = ref()
        const gridReady = (params: any) => {
            gridOption.value = params.api
        }

        const formRef = ref<FormInstance>()
        const sideOk = () => {
            formRef.value?.validate().then((err) => {
                if (!err) {
                    formRef.value?.validate().then((err) => {
                        if (!err) {
                            pageData.pageLoading = true;
                            if (pageData.sideTitle === "新增二维码") {
                                post({
                                    url: "/pdm/CreateQrcode/insert",
                                    data: [dataForm],
                                }).then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.showAdd = false;
                                        Message.success({
                                            content: "新增成功",
                                            duration: 5000,
                                        });
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 5000,
                                        });
                                    }
                                    doRefresh();
                                }).finally(() => {
                                    doRefresh();
                                    pageData.pageLoading = false
                                })
                            } else {
                                post({
                                    url: "/pdm/CreateQrcode/update",
                                    data: [dataForm],
                                }).then((res: any) => {
                                    if (res.code === 200) {
                                        formRef.value?.resetFields();
                                        pageData.showAdd = false;
                                        Message.success({
                                            content: "修改成功",
                                            duration: 5000,
                                        });
                                    } else {
                                        Message.error({
                                            content: res.message,
                                            duration: 5000,
                                        });
                                    }
                                    //doRefresh();
                                }).finally(() => {
                                    doRefresh();
                                    pageData.pageLoading = false
                                })
                            }
                        }
                    });
                }
            })
        }
        const deleteHandler = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选')
                return
            }
            Modal.confirm({
                title: '系统提示',
                content: '确认删除选中的数据?',
                onOk() {
                    pageData.pageLoading = true;
                    post({
                        url: '/pdm/CreateQrcode/delete',
                        data: gridOption.value.getSelectedRows().map((o: any) => { return o.id })
                    }).then(({ code, data }: any) => {
                        if (code === 200) {
                            Message.success({
                                content: '删除成功',
                                duration: 5000
                            })
                            pagination.page = 1
                            doRefresh()
                        } else {
                            Message.error({
                                content: '修改失败',
                                duration: 5000
                            })
                        }
                    }).finally(() => {
                        pageData.pageLoading = false
                    });
                }
            })
        }
        const editHandler = (record: BrandInfo) => {
            selCxAll1({ key: "" })
            //循环对象 赋值
            for (let key in record) {
                dataForm[key] = record[key]
            }
            pageData.sideTitle = '修改二维码'
            pageData.showAdd = true
        }
        //判断是否填写了中文
        const isChiese = (value: string, cb: Function) => {
            return new Promise<void>(resolve => {
                if (window.encodeURI(value).indexOf('%') !== -1) {
                    cb('填写的值只能是英文数字组合或英文，数字！')
                }
                resolve()
            })
        }
        //input离开焦点 将小写转大写
        const inputBlur = () => {
            dataForm.controlMachineCode = dataForm.controlMachineCode.toUpperCase();
            dataForm.remark = dataForm.remark.toUpperCase();
        }
        //导出
        const exports = () => {
            if (gridOption.value.getSelectedRows().length === 0) {
                Message.error('请先勾选');
                return
            } else {
                let idList: any = []
                gridOption.value.getSelectedRows().forEach(function (o: any) {
                    idList.push(o['id'])
                })
                //将表头拼接出来
                let head = "<th>序号</th><th>设备编号</th><th>备注</th><th>创建人</th><th>创建时间</th><th>最后修改人</th><th>最后修改时间</th>"
                //拿到当前表格数据与勾选的行做筛选

                let nowRow = table.dataList.filter(function (o) {
                    return (gridOption.value.getSelectedRows().map((o: any) => { return o.id })).indexOf(o["id"]) !== -1;
                })
                let body = "";
                nowRow.forEach(function (o) {
                    body += "<tr><td>" + o["id"] + "</td>";
                    body += "<td>" + o["controlMachineCode"] + "</td>";
                    body += "<td>" + o["remark"] + "</td>";
                    body += "<td>" + o["createName"] + "</td>";
                    body += "<td>" + o["createTime"] + "</td>";
                    body += "<td>" + o["updateName"] + "</td>";
                    body += "<td>" + o["updateTime"] + "</td>";
                    body += "</tr>";
                })
                tableToXlsx(head, '设备编号', body)
                console.log(table)
            }
        }

        function tableToXlsx(head: any, filename: any, body: any) {
            const uri = 'data:application/vnd.ms-excel;base64,',
                template = `<html>
            <head><meta charset="UTF-8"></head>
            <body><table border="1"><tr>${head}</tr>${body}</table></body>
        </html>`;

            const a = document.createElement('a');
            a.href = uri + window.btoa(unescape(encodeURIComponent(template)));
            a.download = filename;
            a.click();
            document.removeChild(a);
        }

        //模板下载
        const downloadHandler = () => {
            axios.get(baseURL + '/pdm/OperationStep/uploadModel', {
                responseType: 'blob',
                headers: {
                    token: sessionStorage.getItem('USER-TOKEN-KEY')
                }
            }).then((res) => {
                if (res.status === 200) {
                    filedownload(res.data, '设备编号.xlsx')
                }
            })
        }
        //导入
        const importHandler = () => {

            const inputEle: HTMLInputElement = document.createElement('input')
            inputEle.type = 'file'
            inputEle.id = 'fileUploadExcel'
            inputEle.accept = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel'
            inputEle.addEventListener('change', (e) => {
                const formData = new FormData()
                if (inputEle.files !== null) {
                    formData.append('file', inputEle.files[0] || '')
                } else {
                    Message.warning('未选择文件！');
                    return
                }
                pageData.pageLoading = true
                axios.post(baseURL + '/pdm/OperationStep/importModelData', formData, {
                    headers: {
                        "Content-Type": 'multipart/form-data',
                        "token": sessionStorage.getItem('USER-TOKEN-KEY')
                    },
                }).then((result) => {
                    if (result.data['code'] === 200) {
                        Message.success('导入成功')
                    } else {
                        Message.error(result.data.message)
                    }

                }).finally(() => {
                    pageData.pageLoading = false
                    doRefresh()
                })
            })
            inputEle.click()
        }
        //下拉数据 设备编号
        const options1 = ref<any>(pageData.CodeList);
        const loading1 = ref(false);
        const handleSearch1 = (value: any) => {
            if (value) {
                const ob = { controlMachineCode: value, deleteState: 0 }
                loading1.value = true;
                selCxAll1(ob);
                options1.value = pageData.CodeList;
                loading1.value = false;
            } else {
                options1.value = []
            }
        };
        //下拉框查询  设备编号
        function selCxAll1(val: any) {
            post({
                url: "/pdm/controlMachine/getFieldValue",
                data: val
            }).then(({ data, code }: any) => {
                if (code === 200) {
                    pageData.CodeList = data;
                } else {
                    // Message.error({
                    //     content: "查询失败！",
                    //     duration: 5000,
                    // });
                }
            });
        }
        //下拉框得到焦点 设备编号
        const focusSel1 = () => {
            selCxAll1({ "field": "controlMachineCode", deleteState: 0 });
        }

        const sbChange = () => {
            dataForm.controlMachineName = ""
            post({
                url: '/pdm/controlMachine/getList',
                data: {
                    controlMachineCode: dataForm.controlMachineCode
                }
            }).then((res: any) => {
                if (res.code == 200) {
                    dataForm.controlMachineName = res.data[0].controlMachineName
                }
            })
        }
        const NameClick = () => {
            if (dataForm.controlMachineCode == "") {
                Message.warning('请先选择设备编号！')
            }
        }
        //设备编号带出设备名称
        const NameFocus = () => {
            if(dataForm.controlMachineCode != ''){
                post({
                url: "/pdm/controlMachine/getList",
                data: {
                    "controlMachineCode": dataForm.controlMachineCode,
                }
            })
                .then(({ data, code }: any) => {
                    if (code === 200) {
                        pageData.NameList = data
                    }
                })
            }
        }
        const visible = ref(false);
        //生成条码
        let qrData: any = reactive({
            controlMachineCode: "",
            controlMachineName: "",
            qrCode:"",
        })
        const handleOk = () => {
            printJS({
            printable: 'genera',
            type: 'html',
            targetStyles: ['*'],
        })
            visible.value = false;
        };
        const handleCancel = () => {
            visible.value = false;
        }
        const GenerateBtn = (record: any) => {
            visible.value = true;
            qrData.controlMachineCode =record.controlMachineCode;
            qrData.controlMachineName = record.controlMachineName;
            qrData.qrCode = record.qrCode
            qrData.code = JSON.stringify({
                controlMachineCode: encodeURI(record.controlMachineCode),
                controlMachineName: encodeURI(record.controlMachineName),
                qrCode:encodeURI(record.qrCode)
        })
    }
        // //设置权限
        // // ['查询', '新增', '删除', '导出', '导入']
        // const permissionStore = usePermission()

        // if (permissionStore.hasPermisson('ppzl.cx')) {

        //     pageData.btnList.push("查询")
        // }
        // if (permissionStore.hasPermisson('ppzl.xz')) {
        //     pageData.btnList.push("新增")
        // }
        // if (permissionStore.hasPermisson('ppzl.sc')) {
        //     pageData.btnList.push("删除")
        // }
        // if (permissionStore.hasPermisson('ppzl.dc')) {
        //     pageData.btnList.push("导出")
        // }
        // if (permissionStore.hasPermisson('ppzl.dr')) {
        //     pageData.btnList.push("导入")
        // }
        // if (permissionStore.hasPermisson('ppzl.xg')) {
        //     pageData.isEdit = true
        // }
        // console.log(permissionStore.hasPermisson('ppzl.cx'));
        const handleChange = (_data: any) => {
            table.handleSuccess(_data);
        }
        const defaultColDef = {
            sortable: true,
            resizable: true,
            filter: true,
            // flex: 1
        }
        const localeText1:any=ref(localeText)
        const huiche = () => {
            doRefresh();
        }
        return {
            huiche,
            localeText1,
            qrData,
            visible,
            handleOk,
            handleCancel,
            GenerateBtn,
            NameFocus,
            NameClick,
            sbChange,
            editHandler,
            deleteHandler,
            sideOk,
            formRef,
            dataForm,
            addHandler,
            selectedRowKeys,
            pagination,
            tableColumns,
            table,
            rowKey,
            pageData,
            queryData,
            selectHandler,
            isChiese,
            inputBlur,
            exports,
            options,
            loading,
            handleSearch,
            focusSel,
            downloadHandler,
            importHandler,
            options1,
            loading1,
            handleSearch1,
            focusSel1,
            headerShow,
            handleChange,
            PageSize,
            change1,
            defaultColDef,
            tc,
            gridOption,
            gridReady,
            total,
            page,
            size,
        };
    },
    components: { Toolbar, PageTabelLayout,QrcodeVue}
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
    border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}
</style>